import { Button, Card, Form, Input, Space, Tooltip, Table, Modal, message } from "antd";
import React, { Key, useEffect, useState } from "react";
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { ColumnsType } from "antd/lib/table";
import { request } from "@utils/http";
import { batchRemoveHospital, removeHospitalSet, reqGetHospitalSet } from "@/api/hospital/hospitalSet";
import {
  HospitalSetItem,
  HospitalSetItems,
  HospitalSetSearchParams,
} from "@/api/hospital/hospitalSet/types";
import { useForm } from "antd/lib/form/Form";
import { Link } from "react-router-dom";

export default function HospitalSet() {
  //定义一个状态
  let [hospitals, setHospitals] = useState<HospitalSetItems>([]);
  //定义分页相关的状态
  let [total, setTotal] = useState(0);
  let [pageSize, setPageSize] = useState(5);
  let [current, setCurrent] = useState(1);
  //定义 loading 状态
  let [loading, setLoading] = useState(false);
  //导入 useForm 的 hook 函数
  let [form] = useForm();
  //声明一个状态
  let [values, setValues] = useState<HospitalSetSearchParams>({
    hosname: "",
    hoscode: "",
  });
  //声明关于模态框显示的状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  //定义一个状态用来保存要删除的医院 id
  let [removeHosId, setRemoveHosId] = useState(0);
  //定义状态表示选中的医院设置的 id
  let [selectedKeys, setSelectedKeys] = useState<Key[]>([]);
  //声明 onFinish
  let onFinish = async (values: HospitalSetSearchParams) => {
    //表单元素值 values
    //更新状态
    setValues(values);
  };

  // 声明 clear 函数
  let clear = () => {
    //定义一个变量
    let emptyValue = {
      hosname: "",
      hoscode: "",
    };
    //清空
    setValues(emptyValue);
    setCurrent(1);
    //清空表单元素的值
    form.setFieldsValue(emptyValue);
  };

  //点击确定的回调
  let handleOk = async () => {
    setIsModalOpen(false);
    //发送 AJAX 请求删除指定 id 的医院
    await removeHospitalSet(removeHosId);
    //成功提醒
    message.success('删除成功');
    //刷新组件内容
    setValues({...values});
  }

  //点击取消的回调
  let handleCancel = () => {
    console.log('xxx');
    setIsModalOpen(false);
  }

  //发送请求
  useEffect(() => {
    //声明一个 async 函数
    let getHospital = async () => {
      //更新 loading 状态
      setLoading(true);
      //result 变量存储的就是响应体中的 data 属性值
      let result = await reqGetHospitalSet({
        page: current,
        pageSize: pageSize,
        hosname: values.hosname,
        hoscode: values.hoscode,
      });
      //更新状态
      setHospitals(result.records);
      //更新分页的总数状态
      setTotal(result.total);
      //更新 loading 状态
      setLoading(false);
    };
    getHospital();
  }, [current, pageSize, values]);

  //设置表格的结构
  let columns: ColumnsType<HospitalSetItem> = [
    {
      title: "序号",
      // dataIndex:
      render: (value, record, index) => {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机号",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right",
      render: (value, record, index) => {
        return (
          <Space>
            <Tooltip title="修改医院">
              <Link to={`/syt/hospital/hospitalSet/edit/${record.id}`}>
                <Button type="primary" icon={<EditOutlined />}></Button>
              </Link>
            </Tooltip>
            <Tooltip title="删除医院">
              <Button onClick={() => {
                //显示模态框
                setIsModalOpen(true);
                //更新要删除医院的 id 状态
                setRemoveHosId(record.id);
              }} type="primary" danger icon={<DeleteOutlined />}></Button>
              
            </Tooltip>
          </Space>
        );
      },
    },
  ];

  return (
    <Card>
      <Modal
        title="确认信息"
        visible={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>您确定要删除该条数据么??</p>
      </Modal>
      {/* 1. 顶部的表单 */}
      <Form
        form={form}
        name="basic"
        onFinish={onFinish}
        autoComplete="off"
        layout="inline"
      >
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
            <Button onClick={clear}>清空</Button>
          </Space>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 2. 按钮 */}
      <Space>
        <Link to="/syt/hospital/hospitalSet/add">
          <Button type="primary">添加</Button>
        </Link>
        <Button onClick={async () => {
          //发送请求
          await batchRemoveHospital(selectedKeys);
          //提醒
          message.success('删除成功');
          //刷新组件
          setValues({...values});
          //禁用按钮
          setSelectedKeys([]);
        }} disabled={selectedKeys.length === 0}>批量删除</Button>
      </Space>
      {/* 3. 表格 */}
      <div className="h-20"></div>
      <Table
        rowSelection={{
          type: 'checkbox',
          onChange: (selectedRowKeys) => {
            //更新状态
            setSelectedKeys(selectedRowKeys);
          }
        }}
        //设置 loading 属性
        loading={loading}
        //设置哪个属性值作为 key
        rowKey={"id"}
        //表格结构
        columns={columns}
        //表格数据
        dataSource={hospitals}
        //添加边框
        bordered
        //设置滚动宽度
        scroll={{
          x: 1300,
        }}
        //设置分页
        pagination={{
          //分页总数
          total,
          //每页显示的数量
          pageSize,
          //当前页码
          current,
          //显示每页数据调整器
          showSizeChanger: true,
          //调整器的数量设置
          pageSizeOptions: [5, 10, 15, 20],
          //显示总数
          showTotal: (total) => {
            return `总计: ${total} 条`;
          },
          //当页码数以及每页显示数量变化的时候, 自动执行
          onChange: async (page: number, pageSize: number) => {
            //更新状态
            setCurrent(page);
            setPageSize(pageSize);
          },
        }}
      />
    </Card>
  );
}
